<template>
    <div class="search">
        <div class="search-box">
            <van-search @click-input="showSugs(value)" @input="hiddenSugs(value)" autocomplete="off" v-model="value"
                show-action @click-left-icon="searchRecipes(value)" clear-trigger placeholder="请输入菜谱关键词" >
                <template #left>
                    <span class="back" @click="back">&lt;</span>
                </template>
                <template #action>
                    <div @click="cancel">取消</div>
                </template>
            </van-search>
            <div class="search-sugs" :class="{ active: isShow }">

                <ul>
                    <li @click="addKeyword(item.name)" v-for="(item, index) in searchSugsData" :key="index">{{ item.name }}
                        <span class="tag" v-if="item.tag !== undefined"
                            :style="{ background: item.tag.background_color, color: item.tag.text_color, borderBlockColor: item.tag.border_color }">{{
                                item.tag.name }}</span>
                    </li>
                </ul>
                <div class="no-search" v-if="searchSugsData.length===0">
                    <van-empty image="search" description="暂无该菜谱信息" />
                </div>
            </div>
        </div>
        <div class="s-history">
            <div class="h-top">
                <h3>历史搜索</h3>
                <van-icon size="18px" name="delete-o" class="delete" @click="clear" />
            </div>
            <div class="h-bottom" v-if="sHistoryData.length > 0">
                <span class="c-name" v-for="(item, index) in  sHistoryData" @click="addKeyword(item)">{{ item }}</span>
            </div>
            <div class="h-bottom" v-if="sHistoryData.length == 0">
                <p class="no-history">暂无搜索记录!</p>
            </div>
        </div>
        <div class="h-search">
            <h3>热门搜索</h3>
            <ul>
                <li v-for="(item, index) in sugsData" :key="index"
                    :style="{ color: item.color, background: item.background_color }" @click="addKeyword(item.title)">{{
                        item.title }}</li>
            </ul>
        </div>
        <div class="s-list">
            <div class="s-title">
                <h3>豆果推荐</h3>
                <span><van-icon name="replay" @click="replay"/>换一换</span>
            </div>
            <div class="s-content">
                <div class="s-item" v-for="(item,index) in recommendRecipesData" :key="index" @click="goMenuDeatail(item.r.id)">
                    <div class="img-box">
                        <img :src="item.r.img">
                        <span>{{item.r.vc}}人看过</span>
                        <span class="collect">{{item.r.collect_count_text}}</span>
                    </div>
                    <p>{{item.r.n}}</p>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { getHotkeyword, getkeywordSugs, getrecommendRecipes } from "../api/api"
import { showConfirmDialog } from 'vant';
let value: any = ref<string>("")
let router: any = useRouter()
let route: any = useRoute()
let sugsData: any = ref<Array<any>>([])
let isShow: any = ref<boolean>(false)
let searchSugsData: any = ref<Array<any>>([])
let sHistoryData: any = ref<any>("")
let recommendRecipesData: any = ref<Array<any>>([])
//返回
let back: () => void = (): void => {
    router.push(route.query.path)
}
//显示搜索建议
let showSugs: (value: string) => void = (value: string): void => {
    if (value.length === 0) {
        isShow.value = false
    } else {
        isShow.value = true
        //获取搜索关键字建议
        getkeywordSugs(value).then((res: any) => {
            console.log(res)
            searchSugsData.value = res.data.result.suggests
        }).catch((err: any) => {
            console.log(err)
        })
    }
}
//隐藏搜索建议
let hiddenSugs: (value: string) => void = (value: string): void => {
    if (value.length === 0) {
        isShow.value = false
    }
}
//清空文本框
let cancel: () => void = (): void => {
    value.value = "";
    isShow.value = false
}
//添加关键字再文本框上
let addKeyword: (keyword: string) => void = (keyword: string): void => {
    value.value = keyword;
    isShow.value = false
}
//搜索相关菜谱信息
let searchRecipes: (keyword: string) => void = (keyword: string): void => {
    if (keyword.length === 0) {
        return;
    }
    let path: string = "/recipes"
    router.push({
        path, query: {
            kw: keyword,
            path: route.fullPath
        }
    })
    //本地存储搜索历史记录
    sHistoryData.value = localStorage.getItem("sHistoryData")
    if (sHistoryData.value) {
        sHistoryData.value = JSON.parse(sHistoryData.value)
    } else {
        sHistoryData.value = []
    }
    if (sHistoryData.value.length >= 8) {
        sHistoryData.value.pop()
    }
    //判断搜索记录是否相同,同则return,否则push
    for (let i: number = 0; i < sHistoryData.value.length; i++) {
        if (sHistoryData.value[i] == keyword) {
            return;
        }
    }
    sHistoryData.value.unshift(keyword)
    localStorage.setItem("sHistoryData", JSON.stringify(sHistoryData.value))
}
//清空历史记录
let clear: () => void = (): void => {
    showConfirmDialog({
        title: '是否清空历史搜索数据?',
    })
        .then(() => {
            // on confirm
            localStorage.removeItem("sHistoryData")
            sHistoryData.value = []
        })
        .catch(() => {
            // on cancel
        });
}
//换一换
let replay: () => void = (): void => {
    let num:Array<any>=[]
    for(let i:number=0;i<20;i++){
        num.push(i)
    }
    num.sort(():any=>{
        return Math.random()-0.5
    })
    num=num.slice(0,1)
    getrecommend(num[0])
}
//获取推荐菜谱信息
let getrecommend:(index:number)=>void=(index:number):void=>{
    recommendRecipesData.value=[]
    getrecommendRecipes(index).then((res: any) => {
        res.data.result.list.filter((item: any,index:number) => {
            if(index>6){
                return;
            }
            if (item.r) {
                recommendRecipesData.value.push(item)
            }
        })
    }).catch((err: any) => {
        console.log(err)
    })
}
//进入菜谱详情
let goMenuDeatail:(id:string)=>void=(id:string):void=>{
    console.log(id)
    router.push({name:"MenuDetail",params:{menuId:id,path:route.fullPath}})
}
onMounted((): void => {
    //获取热门搜索关键字数据
    getHotkeyword().then((res: any) => {
        sugsData.value = res.data.result.suggestdetails
    }).catch((err: any) => {
        console.log(err)
    })
    //获取本地保存sHistoryData的数据
    sHistoryData.value = localStorage.getItem("sHistoryData")
    if (sHistoryData.value) {
        sHistoryData.value = JSON.parse(sHistoryData.value)
    } else {
        sHistoryData.value = []
        console.log(sHistoryData.value)
    }
    //获取推荐菜谱信息
    getrecommend(0)
})
</script>

<style scoped lang="scss">
.search {
    .search-box {
        position: relative;
        ::v-deep .van-search__content {
            flex: 6;
            border-radius: 4px;
        }
        ::v-deep .van-search{
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            z-index: 1000;
        }
        ::v-deep .van-search__action {
            flex: 1;
            text-align: center;
            color: #333;
        }
        .back {
            font-size: 18px;
            margin-right: 10px;
            display: inline-block;
            width: 25px;
            height: 25px;
            line-height: 25px;
            text-align: center;
        }
        
        .search-sugs {
            background: #fff;
            position: fixed;
            top: 0;
            width: 100%;
            height: 0;
            overflow: hidden;
            left: 0;
            z-index: 999;
            padding: 0 10px;
            box-sizing: border-box;
            transition: height .25s;
            margin-top: 54px;
            &.active {
                height: 100%;
            }

            ul {
                li {

                    display: flex;
                    font-size: 14px;
                    border-bottom: 1px solid #f1f1f1;
                    margin-bottom: 10px;
                    padding-bottom: 5px;

                    &:last-child {
                        border-bottom: none;
                    }

                    .tag {
                        margin-left: auto;
                        display: inline-block;
                        border: 1px solid #f1f1f1;
                        border-radius: 4px;
                        padding: 0 5px;
                    }
                }
            }


        }
    }


    .s-history {
        padding: 10px;
        margin-top: 54px;
        .h-top {
            display: flex;
            align-items: center;

            h3 {
                font-size: 16px;
                font-weight: bold;
            }

            .delete {
                margin-left: auto;
            }
        }

        .h-bottom {
            display: flex;
            flex-wrap: wrap;

            .c-name {
                width: 20%;
                background: #FAFAFA;
                padding: 5px 2px;
                text-overflow: ellipsis;
                white-space: nowrap;
                text-align: center;
                border-radius: 4px;
                margin-bottom: 10px;
                margin-right: 15px;

                &:nth-child(4n) {
                    margin-right: 0;
                }
            }

            .no-history {
                flex: 1;
                text-align: center;
                margin: 0;
                font-size: 14px;
                color: #E2483C;
            }
        }
    }

    .h-search {
        padding: 10px;

        h3 {
            font-size: 16px;
            font-weight: bold;
        }

        ul {
            display: flex;
            flex-wrap: wrap;

            li {
                margin-right: 10px;
                background: #f1f1f1;
                padding: 5px 10px;
                border-radius: 4px;
                text-align: center;
                margin-bottom: 10px;
                margin-right: 15px;

                &:nth-child(-n+2) {
                    border: 1px solid #E2483C;
                    background: transparent;
                    color: #E2483C;

                }
            }
        }
    }

    .s-list {
        padding: 10px;
        .s-title{
            display: flex;
            align-items: center;
            h3 {
            font-size: 16px;
        }
        span{
            margin-left: auto;
            font-size: 14px;
        }
        }
        .s-content {
            display: flex;
            flex-wrap: wrap;
            .s-item {
                width: 33%;
                margin-bottom: 10px;
                text-align: center;
                .img-box{
                    margin: 0 auto;
                    position: relative;
                    width: 110px;
                    height: 110px;
                    img {   
                    width: 100%;
                    height: 100%;
                    border-radius: 4px;
                    }
                  span{
                    display: inline-block;
                    width: 100%;
                    position: absolute;
                    bottom: 0;
                    left: 0;
                    background: rgba(0,0,0,.5);
                    color: #fff;
                    padding: 2px 0;
                  }
                  .collect{
                    top: 0;
                    height: 20px;
                  }
                }
                p {
                    margin: 0;
                    padding: 0 5px;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    overflow: hidden;
                }
            }
        }
    }
}</style>